<template>
  <div id="table-report-city-print">
    <table class="table table-bordered table-sm" v-loading="loading">
      <colgroup>
        <col width="4%" />
        <col width="12%" />
        <col width="12%" />
        <col width="12%" />
        <col width="12%" />
        <col width="12%" />
        <col width="12%" />
        <col width="12%" />
        <col width="12%" />
      </colgroup>
      <thead class="text-center bg-light font-weight-bold table-vertical-middle">
        <tr class="font-weight-bold">
          <td colspan="9" class="bg-white">
            <h3 class="m-0">县级业务台账</h3>
          </td>
        </tr>
        <tr class="font-weight-bold">
          <td colspan="2">填报人</td>
          <td class="bg-white"></td>
          <td colspan="2">联系方式</td>
          <td colspan="4" class="bg-white"></td>
        </tr>
        <tr class="font-weight-bold">
          <td colspan="2">填报说明</td>
          <td colspan="7" class="bg-white text-left">
            <ul class="list-unstyled">
              <li>
                1、县（区）名称，必须以县、县级市、区等县级行政单位为标准填写，不要填写地级市。没有业务的县（区）请不要在此表中填写。
              </li>
              <li>
                2、本年新增、累计新增、期末在保各项数据必须与《省级农担公司业务发展情况统计月报》统计数值保持一致。
              </li>
              <li>
                3、农业大县业务覆盖率：以下表为基础，计算121号文以来有新增业务的县对农业大县的覆盖率，农业大县名单以农业农村部、财政部印发版为准，新名单未印发前，暂不需填写。
              </li>
            </ul>
          </td>
        </tr>
        <tr class="font-weight-bold">
          <td colspan="2">农业大县业务覆盖率</td>
          <td colspan="7" class="bg-white"></td>
        </tr>
        <tr>
          <td rowspan="2">序号</td>
          <td rowspan="2">县（区）名称</td>
          <td rowspan="2">该县所属地级市</td>
          <td colspan="2">本年新增</td>
          <td colspan="2">121号文以来累计新增</td>
          <td colspan="2">在保</td>
        </tr>
        <tr>
          <td>
            <div>担保金额</div>
            （万元）
          </td>
          <td>项目数</td>
          <td>
            <div>担保金额</div>
            （万元）
          </td>
          <td>项目个数</td>
          <td>
            <div>余额</div>
            （万元）
          </td>
          <td>项目个数</td>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in tableData" :key="index">
          <td class="text-right">{{ index + 1 }}</td>
          <td class="text-center">{{ item.address_code_name }}</td>
          <td class="text-center">{{ item.city_code_name }}</td>
          <td class="text-right" data-alignment-horizontal="right">
            {{ item.in_gua_funds_current_year }}
          </td>
          <td class="text-right" data-alignment-horizontal="right">
            {{ item.in_gua_total_current_year }}
          </td>
          <td class="text-right" data-alignment-horizontal="right">{{ item.in_gua_funds }}</td>
          <td class="text-right" data-alignment-horizontal="right">{{ item.in_gua_total }}</td>
          <td class="text-right" data-alignment-horizontal="right">
            {{ item.in_gua_funds_current_quarter }}
          </td>
          <td class="text-right" data-alignment-horizontal="right">
            {{ item.in_gua_total_current_quarter }}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { add, sub, excelTableExport } from '@vimi/utils-tool'
// import { findLastIndex } from '@/common/plugins/tools/array'
import { enumQuarter } from '@/credit/views/city/report/reportMixins'

const matchKeys = [
  { key: 'address_code', type: 's' },
  { key: 'address_code_name', type: 's' },
  { key: 'city_code_name', type: 's' },
  { key: 'in_gua_funds', type: 'n' },
  { key: 'in_gua_funds_current_quarter', type: 'n' },
  { key: 'in_gua_funds_current_year', type: 'n' },
  { key: 'in_gua_total', type: 'n' },
  { key: 'in_gua_total_current_quarter', type: 'n' },
  { key: 'in_gua_total_current_year', type: 'n' },
  { key: 'order_num', type: 's' },
]
const matchCopy = d =>
  matchKeys.reduce((p, c) => {
    p[c.key] = d[c.key]
    return p
  }, {})
// const matchEqual = (a, b) => {
//   for (const c of matchKeys) {
//     let av = a[c.key]
//     let bv = b[c.key]
//     if (c.type === 'n') {
//       av = +av
//       bv = +bv
//     }
//     if (av !== bv) {
//       return false
//     }
//   }
//   return true
// }

export default {
  components: {},
  props: {
    addressCode: String,
    queryYear: Number,
    queryQuarter: Number,
  },
  data() {
    return {
      loading: false,
      refreshLoading: false,
      tableName: 'report_quarter',
      subTableName: 'report_quarter_detail',
      tableData: [],
      reportData: {},
    }
  },
  computed: {
    ...mapGetters(['clientId']),
    quarter() {
      return `${this.queryYear}-${this.queryQuarter}`
    },
    dateLabel() {
      return `${this.queryYear}年第${enumQuarter[this.queryQuarter]}季度`
    },
  },
  watch: {
    quarter: {
      handler: 'handleDateQuery',
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async getData(year, quarter) {
      this.loading = true
      this.$emit('loading', true)
      const [res, err] = await this.$utils.promise(this.apiReportData(year, quarter))
      this.loading = false
      this.$emit('loading', false)

      if (err) {
        return this.$message.error('获取报表数据失败')
      }

      if (res && res.report && res.report.report_quarter_id) {
        this.reportData = res.report
        this.tableData = res.details
      } else {
        this.getLastQuarterData(year, quarter).then(res => {
          this.tableData = res.details
          this.reportData = res.report

          // 保存本季度数据
          this.saveReportData({
            year,
            quarter: quarter,
            data: this.tableData,
          })
        })
      }
    },

    // 获取上一季度和当前季度值为计算
    getLastQuarterData(year, quarter) {
      const currentQuarter = quarter
      quarter--
      if (quarter < 1) {
        quarter = 4
        year--
      }

      this.loading = true
      this.$emit('loading', true)
      return Promise.all([
        this.apiReportData(year, quarter),
        this.apiCurrentQuarterData(year, currentQuarter),
      ])
        .then(([lastReportData, quarterData]) => {
          const { report, details } = lastReportData

          // current quarter data
          const cqMap = new Map()
          for (const d of quarterData) {
            cqMap.set(+d.lever_code, d)
          }

          const isFirstQuarter = currentQuarter === 1

          for (const detail of details) {
            const cityCode = detail.address_code.substring(0, 6)
            detail.lever_code = +cityCode
            detail.city_code = ~~(detail.lever_code / 1e2) * 1e2

            if (!cqMap.has(cityCode)) {
              continue
            }

            const cq = cqMap.get(cityCode)
            cqMap.delete(cityCode)

            // 本年新增
            if (!isFirstQuarter) {
              detail.in_gua_funds_current_year = add(
                detail.in_gua_funds_current_year,
                cq.current_quarter_new_funds
              )
              detail.in_gua_total_current_year = add(
                detail.in_gua_total_current_year,
                cq.current_quarter_new_total
              )
            } else {
              detail.in_gua_funds_current_year = cq.current_quarter_new_funds
              detail.in_gua_total_current_year = cq.current_quarter_new_total
            }

            // 121号文以来累计新增
            detail.in_gua_funds = add(detail.in_gua_funds, cq.current_quarter_new_funds)
            detail.in_gua_total = add(detail.in_gua_total, cq.current_quarter_new_total)

            // 在保
            detail.in_gua_funds_current_quarter = sub(
              add(detail.in_gua_funds_current_quarter, cq.current_quarter_new_funds),
              cq.current_quarter_new_un_funds
            )
            detail.in_gua_total_current_quarter = sub(
              add(detail.in_gua_total_current_quarter, cq.current_quarter_new_total),
              cq.current_quarter_new_un_total
            )
          }

          // 添加数据
          // for (const [key, cq] of cqMap) {
          //   const itemData = {
          //     address_code: `${cq.lever_code}`.padEnd(12, '0'),
          //     address_code_name: cq.address_code_name,
          //     city_code_name: '',
          //     order_num: 1,
          //     in_gua_funds_current_year: cq.current_quarter_new_funds,
          //     in_gua_total_current_year: cq.current_quarter_new_total,
          //     in_gua_funds: cq.current_quarter_new_funds,
          //     in_gua_total: cq.current_quarter_new_total,
          //     in_gua_funds_current_quarter: sub(cq.current_quarter_new_funds, cq.current_quarter_new_un_funds),
          //     in_gua_total_current_quarter: sub(cq.current_quarter_new_total, cq.current_quarter_new_un_total)
          //   }
          //   const index = findLastIndex(details, it => key > it.city_code && key < (it.city_code + 100))
          //   if (index > -1) {
          //     itemData.order_num = index + 2
          //     itemData.city_code_name = details[index].city_code_name
          //     details.splice(index + 1, 0, itemData)
          //     for (let i = index + 1; i < details.length; i++) {
          //       details[i].order_num++
          //     }
          //   } else {
          //     itemData.order_num = details.length
          //     details.push(itemData)
          //   }
          // }

          return { details, report }
        })
        .finally(() => {
          this.loading = false
          this.$emit('loading', false)
        })
    },

    apiCurrentQuarterData(year, quarter) {
      return this.$api
        .getData(this.$serviceName, 'quarter_report_analysis_view', {
          isBIQuery: 1,
          'quarter_num.eq': quarter,
          'service_id.eq': this.clientId,
        })
        .then(res => res.data || [])
    },

    apiReportData(year, quarter) {
      return this.$api
        .getData(this.$serviceName, this.tableName, {
          'year_number.eq': year,
          'quarter_number.eq': quarter,
          subKey: `${this.subTableName}.report_quarter_id`,
        })
        .then(res => {
          const data = ((res && res.data) || [])[0] || {}
          const { report_quarter_detail: quarterDetail, ...report } = data
          const details = (quarterDetail || [])
            .map(item => {
              item.order_num = +item.order_num
              return item
            })
            .sort((a, b) => (+a.order_num > +b.order_num ? 1 : -1))
          // for (const d of details) {
          //   // 处理金额格式：加逗号、保留两位小数点
          //   d.in_gua_funds_dot = formatFunds(+d.in_gua_funds)
          //   d.current_year_new_funds_dot = formatFunds(+d.current_year_new_funds)
          //   d.on_gua_funds_dot = formatFunds(d.on_gua_funds)
          // }
          return { report, details }
        })
    },

    apiReportDelete(reportId) {
      // 500错误
      // return this.$api.relatedDelete('credit', {
      //   isRetainMasterInfo: '0',
      //   masterTableInfo: JSON.stringify({
      //     report_quarter_id: reportId
      //   }),
      //   masterTableName: this.tableName,
      //   slaveTableName: this.subTableName
      // })

      return Promise.all([
        this.$api.deleteData(this.$serviceName, this.tableName, reportId),
        this.$api.deleteDataBody(this.$serviceName, this.subTableName, {
          report_quarter_id: reportId,
        }),
      ])
    },

    saveReportData({ year, quarter, data }) {
      const masterData = {
        quarter_number: quarter,
        report_name: `${year}第${enumQuarter[quarter]}季度报表`,
        year_number: year,
      }

      const slaveData = []
      for (const d of data) {
        slaveData.push(matchCopy(d))
      }
      const postData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: this.tableName,
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: this.subTableName,
      }

      this.loading = true
      return this.$api
        .relatedBatch(this.$serviceName, postData)
        .then(res => {
          this.$emit('success', res)
        })
        .catch(() => {
          this.$message.error('新增报表失败！')
        })
        .finally(() => {
          this.loading = false
        })
    },

    /**
     * 刷新报表，先删除，后添加
     */
    async refreshReport() {
      const {
        queryYear,
        queryQuarter,
        reportData: { report_quarter_id: reportId },
      } = this
      if (!reportId) return

      this.loading = true
      this.getLastQuarterData(queryYear, queryQuarter)
        .then(res => {
          return this.apiReportDelete(reportId).then(() => res)
        })
        .then(res => {
          return this.saveReportData({
            year: queryYear,
            quarter: queryQuarter,
            data: res.details,
          })
        })
        .then(() => {
          this.$message.success('刷新报表成功！')
        })
        .catch(() => {
          this.$message.error('刷新报表失败！')
        })
        .finally(() => {
          this.loading = false
        })
    },

    deleteReport() {
      const {
        reportData: { report_quarter_id: reportId },
      } = this
      return this.apiReportDelete(reportId)
        .then(() => {
          this.$message.success('删除报表成功！')
        })
        .catch(() => {
          this.$message.error('删除报表失败！')
        })
    },

    handleDateQuery() {
      const { queryYear, queryQuarter } = this

      if (!queryYear || !queryQuarter) {
        return
      }

      this.getData(queryYear, queryQuarter)
    },

    onExportExcel() {
      const borderAllThin = {
        left: { style: 'thin' },
        top: { style: 'thin' },
        right: { style: 'thin' },
        bottom: { style: 'thin' },
      }
      const bgGray = { fgColor: { rgb: 'FFA6A6A6' } }
      const cellStyles = {}
      for (let i = 0; i < 9; i++) {
        cellStyles[`0-${i}`] = { font: { bold: true } }
        cellStyles[`1-${i}`] = { font: { bold: true } }
        cellStyles[`2-${i}`] = { font: { bold: true } }
        cellStyles[`3-${i}`] = { font: { bold: true } }
        cellStyles[`4-${i}`] = { font: { bold: true }, fill: bgGray }
        cellStyles[`5-${i}`] = { font: { bold: true }, fill: bgGray }
      }
      cellStyles['1-0'].fill = bgGray
      cellStyles['1-3'].fill = bgGray
      cellStyles['2-0'].fill = bgGray
      cellStyles['3-0'].fill = bgGray
      cellStyles['2-2'].alignment = { horizontal: 'left' }

      return excelTableExport('table-report-city-print', `${this.dateLabel}县级业务台账`, {
        styles: {
          border: borderAllThin,
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        cellStyles,
        cols: [
          { wch: 5.13 },
          { wch: 13.5 },
          { wch: 15.75 },
          { wch: 14.13 },
          { wch: 14.13 },
          { wch: 14.13 },
          { wch: 14.13 },
          { wch: 14.13 },
          { wch: 14.13 },
        ],
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
